package one.stand.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import one.stand.aop.ApiController;
import one.stand.exception.ParamException;
import one.stand.model.DynamicModel;
import one.stand.model.ResultModel;
import one.stand.model.essay.TaskCustomerModel;
import one.stand.request.BaseRequest;
import one.stand.request.BusinessCardRequest;
import one.stand.request.DynamicRequest;
import one.stand.request.GoodsRequest;
import one.stand.request.essay.*;
import one.stand.response.BusinessCardResponse;
import one.stand.response.DynamicResponse;
import one.stand.response.GoodstypeResponse;
import one.stand.response.essay.*;
import one.stand.service.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 获客文章类型相关业务
 * @author luoyang
 * @date 2020/5/7 11:38
 */
@RestController
@RequestMapping("customerEssay")
@Slf4j
public class CustomerEssayController {

//    @Autowired
//    private CustomerEssayService customerEssayService;

    @Autowired
    private IEssayStaffDataService essayStaffDataService;

    @Autowired
    private IEssayVisitorsDataService iEssayVisitorsDataService;

    @Autowired
    private IEssayShareRecordService iEssayShareRecordService;

    @Autowired
    private IDynamicService iDynamicService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ITaskCustomerSerivce taskCustomerSerivce;

    @Autowired
    private ITaskStaffService iTaskStaffService;

    @Autowired
    private BusinessCardService businessCardService;

    /**
     * 员工数据查询
     * @param request
     * @return
     */
    @PostMapping("queryStaffData")
    public ResultModel<PageInfo<EssayStaffDataResponse>> queryStaffData(@RequestBody @Valid EssayStaffDataRequest request){
        log.info("queryStaffData:{}",request);
        return essayStaffDataService.queryStaffData(request);
    }

    /**
     * 添加或更新获客文章员工数据
     * @param request
     * @return
     */
    @PostMapping("addStaffData")
    public ResultModel<Boolean> addStaffData(@RequestBody @Valid EssayStaffDataFrom request){
        log.info("addStaffData:{}",request);
        return essayStaffDataService.addStaffData(request);
    }

    /**
     * 添加或更新访客数据
     * @param request
     * @return
     */
    @PostMapping("addVisitorsData")
    public ResultModel<Boolean> addVisitorsData(@RequestBody @Valid EssayVisitorsDataForm request) throws ParamException {
        log.info("addVisitorsData:{}",request);
        return iEssayVisitorsDataService.addVisitorsData(request);
    }


    /**
     * 添加或更新员工分享数据
     * @param request
     * @return
     */
    @PostMapping("addShareRecordData")
    public ResultModel<Boolean> addShareRecordData(@RequestBody @Valid EssayRecordForm request) throws ParamException {
        log.info("addShareRecordData:{}",request);
        return iEssayShareRecordService.addShareRecordData(request);
    }

    /**
     * 员工分享详情
     * @param request
     * @return
     */
    @PostMapping("queryStaffShareDetail")
    public ResultModel<PageInfo<EssayShareDetailResponse>> queryStaffShareDetail(@RequestBody @Valid EssayShareDetailRequest request){
        log.info("queryStaffShareDetail:{}",request);
        return essayStaffDataService.queryStaffShareDetail(request);
    }


    /**
     * 访客数据查询
     * @param request
     * @return
     */
    @PostMapping("queryVisitorsData")
    public ResultModel<PageInfo<EssayVisitorsDataResponse>> queryVisitorsData(@RequestBody @Valid EssayVisitorsDataRequest request){
        log.info("queryVisitorsData:{}",request);
        return iEssayVisitorsDataService.queryVisitorsData(request);
    }


    /**
     * 文章查询 ，按条件查询 已分享的 或者企业文库  ,企业文库里面的文章只要分享过的都会出现在已分享，不算企业文库
     * @param request
     * @return
     */
    @PostMapping("queryDynamicData")
    public ResultModel<PageInfo<DynamicModelResponse>> queryDynamicData(@RequestBody @Valid DynamicQuery request){
        log.info("queryDynamicData:{}",request);
        return iDynamicService.queryDynamicData(request);
    }

    /**
     * 删除已经分享的文章
     * @param request
     * @return
     */
    @PostMapping("deleteByDynamicId")
    public ResultModel<Boolean> deleteByDynamicId(@RequestBody @Valid CompanyDynamicsQuery request){
        log.info("deleteByDynamicId:{}",request);
        return iDynamicService.deleteByDynamicId(request);
    }

    /**
     * 查询文章访客详情 倒叙排列
     * @param request
     * @return
     */
    @PostMapping("queryDynamicVisitors")
    public ResultModel<DynamicModelResponse> queryDynamicVisitors(@RequestBody @Valid VisitorsDetailQuery request){
        log.info("queryDynamicVisitors:{}",request);
        return iDynamicService.queryDynamicVisitors(request);
    }


    /**
     * 按商品分类查询公司下的商品
     * @param request
     * @return
     */
    @PostMapping("queryCompanyGoods")
    public ResultModel<PageInfo<CompanyGoodsTypeResponse>> queryCompanyGoods(@RequestBody @Valid GoodsQuery request){
        log.info("queryCompanyGoods:{}",request);
        return goodsService.queryCompanyGoods(request);
    }

    /**
     * 查询公司下的文章
     * @param request
     * @return
     */
    @PostMapping("queryCompanyDynamics")
    public ResultModel<PageInfo<DynamicModelResponse>> queryCompanyDynamics(@RequestBody @Valid CompanyDynamicsQuery request){
        log.info("queryCompanyDynamics:{}",request);
        return iDynamicService.queryCompanyDynamics(request);
    }


    /**
     * 查询文章详情
     * @param request
     * @return
     */
    @PostMapping("queryCompanyDynamicById")
    public ResultModel<DynamicDetailResponse> queryCompanyDynamicById(@RequestBody @Valid CompanyDynamicsQuery request){
        log.info("queryCompanyDynamicById:{}",request);
        if(request.getDynamicId() == null){
            return ResultModel.noData();
        }
        return iDynamicService.queryCompanyDynamicById(request);
    }


    /**
     * 添加获客文章任务 更新也使用此接口
     * @param request
     * @return
     */
    @PostMapping("addTaskCustomer")
    public ResultModel<Boolean> addTaskCustomer(@RequestBody @Valid TaskCustomerForm request) throws ParamException {
        log.info("addTaskCustomer:{}",request);
        return taskCustomerSerivce.addTaskCustomer(request);
    }

    /**
     * 查询获客文章任务-全员营销
     * @param request
     * @return
     */
    @PostMapping("queryTaskCustomer")
    public ResultModel<TaskCustomerResponse> queryTaskCustomer(@RequestBody @Valid TaskCustomerQuery request) throws ParamException {
        log.info("queryTaskCustomer:{}",request);
        return taskCustomerSerivce.queryTaskCustomer(request);
    }

    /**
     *查询我的任务列表
     * @param request
     * @return
     */
    @PostMapping("queryMyTask")
    public ResultModel queryMyTask(@RequestBody @Valid MyTaskQuery request) throws ParamException {
        log.info("queryMyTask:{}", JSONObject.toJSONString(request));
        if(request.getUserId() == null){
            request.setUserId(request.getId());
        }
        return iTaskStaffService.queryMyTask(request);
    }

    /**
     *查询我的任务详情
     * @param request
     * @return
     */
    @PostMapping("queryMyTaskDetail")
    public ResultModel<MyTaskResponse> queryMyTaskDetail(@RequestBody @Valid MyTaskDetailQuery request) throws ParamException {
        log.info("queryMyTaskDetail:{}",request);
        return iTaskStaffService.queryMyTaskDetail(request);
    }

    /**
     * 更新我的任务状态 state为空则更新查看状态 不为空则更新任务状态
     * @param request
     * @return
     */
    @PostMapping("updateMyTaskState")
    public ResultModel<Boolean> updateMyTaskState(@RequestBody @Valid UpdateMyTaskFrom request) throws ParamException {
        log.info("updateMyTaskState:{}",request);
        if(request.getUserId() == null){
            request.setUserId(request.getId());
        }
        return this.iTaskStaffService.updateMyTaskState(request);
    }


    /**
     * 更新我发布的任务状态 state为空则更新查看状态 不为空则更新任务状态
     * @param request
     * @return
     */
    @PostMapping("updateMyPubTaskState")
    public ResultModel<Boolean> updateMyPubTaskState(@RequestBody @Valid UpdateMyTaskFrom request) throws ParamException {
        log.info("updateMyTaskState:{}",request);
        if(request.getUserId() == null){
            request.setUserId(request.getId());
        }
        return this.iTaskStaffService.updateMyPubTaskState(request);
    }

    /**
     * 查询公司员工
     * @param request
     * @return
     * @throws ParamException
     */
    @PostMapping("queryCompanyStaff")
    public ResultModel<List<BusinessCardResponse>> queryCompanyStaff(@RequestBody @Valid BusinessCardRequest request) throws ParamException {
        log.info("queryCompanyStaff:{}",request);
        return businessCardService.queryCompanyStaff(request);
    }

    /**
     * 转载文章解析
     * @param request
     * @return
     * @throws ParamException
     */
    @PostMapping("reprintArticle")
    @ApiController(isLogin = true,company = true,card = true,paramClass = ReprintArticleForm.class)
    public ResultModel<ReprintArticleResponse> reprintArticle(@RequestBody @Valid ReprintArticleForm request) throws IOException {
        log.info("reprintArticle:{}",request);
        ReprintArticleResponse reprintArticleResponse = new ReprintArticleResponse();
        Document doc = Jsoup.connect(request.getUrl()).get();
        Elements s = doc.getElementsByTag("img");
        if(Optional.ofNullable(s).isPresent()){
            reprintArticleResponse.setCoverImg(getImg(s));
        }

        reprintArticleResponse.setName(doc.getElementById("js_name").text());
        reprintArticleResponse.setTitle(doc.getElementById("activity-name").text());
        reprintArticleResponse.setAuthor(doc.getElementsByClass("rich_media_meta_text").text());

        String html = doc.getElementById("js_content").toString();
        //替换image 属性
        html = html.replaceAll("data-src","src");
        //替换css属性为显示
        html = html.replaceAll("visibility: hidden","") ;
        html = html.replaceAll("style=\"width: 100%;height: auto;","style=\"max-width: 100%;height: auto; ") ;
        html = html.replaceAll("style=\"\"","style=\"max-width: 100%;height: auto;\" ") ;
        html = html.replaceAll("\\?wx_fmt=jpeg","") ;
        html = html.replaceAll("\\?wx_fmt=gif","") ;
        html = html.replaceAll("\\?wx_fmt=png","") ;
        html = html.replaceAll(" width: 677px !important;"," width: 100%;") ;


        reprintArticleResponse.setBody(html);

        return ResultModel.success(reprintArticleResponse);
    }

    /**
     * 取第一个不为空的图片
     * @param elements
     * @return
     */
    private static String getImg(Elements elements){
        return elements.stream().filter(element -> !element.attr("data-src").equals("")).findFirst().get().attr("data-src");
    }


    @PostMapping("getDynamic")
    @ApiController(isLogin = false,company = false,card = false,paramClass = H5GetDynamic.class)
    public ResultModel<Map<String,Object>> getDynamic(@RequestBody @Valid H5GetDynamic request) throws IOException {
        log.info("getDynamic:{}",request);
        Map<String,Object> maps = new HashMap<>();

        if(!StringUtils.isEmpty(request.getDynamicId())){
//            DynamicDetailResponse dynamicModel = this.iDynamicService.queryById(request.getDynamicId());
            maps.put("dynamicInfo", iDynamicService.queryCompanyDynamicById(new CompanyDynamicsQuery(){{setDynamicId(Integer.valueOf(request.getDynamicId()));}}).getData());
        }

        if(!StringUtils.isEmpty(request.getUserId())){
            BusinessCardResponse response = this.businessCardService.queryUserById(request.getUserId());
            maps.put("userInfo",response);
        }

        return ResultModel.success(maps);
    }



}
